'use client';

import { useState } from "react";
import { useRouter } from "next/navigation";
import { toast } from "react-hot-toast";
import styles from "./forgot-password.module.css";

const ForgotPasswordPage = () => {
  const router = useRouter();
  const [loading, setLoading] = useState(false);
  const [email, setEmail] = useState("");

  const handleSubmit = async (e) => {
    e.preventDefault();
    setLoading(true);

    try {
      const res = await fetch("/api/auth/forgot-password/send-code", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email })
      });

      const data = await res.json();
      if (!res.ok) {
        throw new Error(data.error || "发送验证码失败");
      }

      toast.success(data.message);
      // 跳转到验证码页面，并携带邮箱参数
      router.push(`/dashboard/forgot-password/verify?email=${encodeURIComponent(email)}`);
    } catch (err) {
      toast.error(err.message);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className={styles.container}>
      <h1 className={styles.title}>忘记密码</h1>
      <p className={styles.subtitle}>请输入您的注册邮箱，我们将发送验证码到该邮箱</p>

      <form onSubmit={handleSubmit} className={styles.form}>
        <div className={styles.formGroup}>
          <label className={styles.label}>邮箱地址</label>
          <input
            type="email"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            className={styles.input}
            placeholder="请输入注册邮箱"
            required
          />
        </div>

        <button
          type="submit"
          disabled={loading}
          className={styles.button}
        >
          {loading ? "发送中..." : "发送验证码"}
        </button>

        <button
          type="button"
          onClick={() => router.push("/dashboard/login")}
          className={styles.cancelButton}
        >
          返回登录
        </button>
      </form>
    </div>
  );
};

export default ForgotPasswordPage;